<!--
纪工委工单
 * @Author: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @Date: 2025-05-25 16:46:30
 * @LastEditors: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @LastEditTime: 2025-06-02 22:55:23
 * @FilePath: \iam-ui\src\views\disciplinary\workOrder\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="work">
    <div class="work-top">
      <div class="work-top-item">
        <div class="title">待处理工单数</div>
        <div class="num">{{ dwCountMap.dcl }}个工单</div>
      </div>
      <div class="work-top-item">
        <div class="title">本周处理工单数</div>
        <div class="num">{{ dwCountMap.ycl_week }}个工单</div>
      </div>
      <div class="work-top-item">
        <div class="title">本年累计工单数</div>
        <div class="num">{{ dwCountMap.year }}个工单</div>
      </div>
    </div>
    <div class="work-table">
      <el-form
        :model="searchForm"
        class="search-form"
        inline
        style="margin-bottom: 12px"
      >
        <el-form-item label="工单编号">
          <el-input
            v-model="searchForm.workOrderNumber"
            placeholder="请输入工单编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="工单来源">
          <el-select
            v-model="searchForm.source"
            placeholder="请选择工单来源"
            clearable
          >
            <el-option label="12345" value="12345" />
            <el-option label="公共号" value="公共号" />
            <!-- 可根据实际来源类型补充 -->
          </el-select>
        </el-form-item>
        <el-form-item label="处理类型">
          <el-select v-model="searchForm.mark" placeholder="处理类型" clearable>
            <el-option label="未处理" value="未处理" />
            <el-option label="督办-未回复" value="督办-未回复" />
            <el-option label="督办-已回复" value="督办-已回复" />
            <el-option label="已阅" value="已阅" />
          </el-select>
        </el-form-item>
        <el-form-item label="督办日期">
          <el-date-picker
            v-model="searchForm.superviseTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="请选择督办日期区间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item style="margin-right: 0">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" stripe>
        <el-table-column prop="source" label="工单来源" show-overflow-tooltip />
        <el-table-column
          prop="workOrderNumber"
          label="工单编号"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workOrderSubject"
          label="工单主题"
          show-overflow-tooltip
        />
        <el-table-column prop="mark" label="处理类型" show-overflow-tooltip>
          <template #default="{ row }">
            <span
              :style="{
                color: row.mark === '督办-未回复' ? '#ff4d4f' : 'inherit',
              }"
            >
              {{ row.mark }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="complaintCategoryLevel1"
          label="诉求分类（一级）"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workOrderSubject"
          label="工单主题"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workOrderContent"
          label="工单内容"
          show-overflow-tooltip
        />
        <el-table-column
          prop="superviseTime"
          label="督办日期"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="handleOptions(row, 'view')"
              >详情</el-button
            >
            <el-button
              v-if="row.mark === '督办-未回复'"
              type="text"
              @click="onReplyDrawerClick(row, 'reply')"
              >回复</el-button
            >
            <el-button
              v-else-if="
                row.mark === '督办-已回复' || row.mark === '督办-未回复'
              "
              type="text"
              @click="onReplyDrawerClick(row, 'view')"
              >查看回复</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-count">总共 {{ total }} 个项目</span>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next, jumper, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 抽屉组件 -->
    <reply-drawer
      v-model:visible="replyDrawerVisible"
      :mode="replyDrawerMode"
      :work-order-data="currentAssetData"
      :reply-list="replyList"
      @submit="handleReplySubmit"
      @cancel="handleReplyCancel"
    />

    <detail-drawer
      v-if="drawerVisible"
      v-model:visible="drawerVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
      :page-type="'纪工委工单'"
    />
  </div>
</template>

<script setup>
import CommonDrawer from "@/components/CommonDrawer.vue";
import ReplyDrawer from "@/components/ReplyDrawer.vue";
import { onMounted, reactive, defineAsyncComponent } from "vue";
import {
  getDepartMentWorkOrdersList,
  postReply,
  getReplyList,
  getDWCountMap,
} from "./services";
import { getInfo } from "@/api/workOrder";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

const userStore = useUserStore();

const DetailDrawer = defineAsyncComponent(() =>
  import("@/components/DetailDrawer.vue")
);
// 表格数据
const tableData = ref([]);
const total = ref(0);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
// 抽屉控制
const drawerVisible = ref(false);
const drawerType = ref("");
const currentAssetData = ref(null);
const replyDrawerVisible = ref(false);
const replyDrawerMode = ref("reply");
const replyList = ref([]);

// 搜索表单字段与接口、表格字段完全一致
const searchForm = reactive({
  workOrderNumber: "", // 工单编号
  mark: "", // 处理状态
  source: "", // 工单来源
  superviseTimeRange: [], // 督办日期区间
});

// 纪工委统计数据
const dwCountMap = ref({ ycl_week: 0, year: 0, dcl: 0 });

const handleOptions = (row, type) => {
  if (type !== "delete") {
    drawerVisible.value = true;
    drawerType.value = type;
    currentAssetData.value = row;
  }
};

const onReplyDrawerClick = async (row, mode) => {
  currentAssetData.value = row;
  replyDrawerVisible.value = true;
  replyDrawerMode.value = mode;
  if (mode === "view") {
    // 获取工单回复列表
    const departmentId = userStore.dept.deptId;
    const orderId = row.id || row.orderId;
    const res = await getReplyList({ orderId, departmentId });
    if (res.code === 200) {
      replyList.value = res.rows || res.data || [];
    } else {
      replyList.value = [];
    }
  }
};

const handleReplySubmit = async (replyContent) => {
  const orderId = currentAssetData.value?.id;
  const departmentId = userStore.dept.deptId;
  try {
    await postReply({ orderId, departmentId, replyContent });
    ElMessage.success("回复成功");
    fetchTableData();
  } catch (e) {
    ElMessage.error("回复失败");
  }
};

const handleReplyCancel = () => {
  replyDrawerVisible.value = false;
};

// 获取表格数据
const fetchTableData = async () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    departmentId: userStore.dept.deptId,
    ...searchForm,
  };
  // 处理督办日期区间
  if (params.superviseTimeRange && params.superviseTimeRange.length === 2) {
    params.params = {
      beginTime: dayjs(params.superviseTimeRange[0]).format(
        "YYYY-MM-DD 00:00:00"
      ),
      endTime: dayjs(params.superviseTimeRange[1]).format(
        "YYYY-MM-DD 23:59:59"
      ),
    };
    delete params.superviseTimeRange;
  }
  const res = await getDepartMentWorkOrdersList(params);
  if (res.code !== 200) {
    tableData.value = [];
    total.value = 0;
    return;
  }
  tableData.value = res.rows || [];
  total.value = res.total || 0;
};
const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

onMounted(() => {
  fetchTableData();
  // 获取纪工委统计数据，传递 departmentId
  getDWCountMap({ departmentId: userStore.dept.deptId }).then((res) => {
    if (res.code === 200 && res.data) {
      dwCountMap.value = res.data;
    }
  });
});
</script>

<style lang="scss" scoped>
@import "./index.scss";

.search-form {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}
</style>
